import threading
import time

counter = 0
# 锁
counter_lock = threading.Lock()

def increment():
    global counter
    with counter_lock:  # 使用with语句可以自动获取和释放锁
        local_counter = counter
        time.sleep(0.001)
        local_counter += 1
        counter = local_counter

threads = []
for i in range(1000):
    thread = threading.Thread(target=increment)
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()

print("Counter:", counter)